<?php
// +----------------------------------------------------------------------
// | 父类控制器.继承自builder,可自定义或重写任意方法
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\business\controller;

use think\exception\ValidateException;
use think\facade\View;
use think\response\Json;

abstract class Base extends \app\common\builder\TableBase
{
    public $business;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->business = $this->request->business;
        View::assign('_business', $this->business);
    }

    /**
     * @param array $param -- 新增或修改的数据，支持直接调用和间接调用
     * @param array $model -- 调用model方法，默认false
     *
     * 原点 2021年7月27日14:46:07 公共新增/修改方法
     */
    public function save($param = [], $model = false): Json
    {
        $param = empty($param) ? $this->request->post() : $param;

        if (!isset($param[$this->pk]) && isset($this->validate)) {
            try {
                $this->validate($param, $this->validate);
            } catch (ValidateException $e) {
                return json(['code' => -1, 'msg' => $e->getError()]);
            }

        }
        $param['business_id'] = $this->business->id;
        if ($model) {
            $result = $this->model::_save($param, $this->admin);
        } else {
            $result = $this->model::_magic($param, $this->admin);
        }

        return json($result);
    }
}
